#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>

#include "./../003Head/head.h"

int main()
{
    //1.创建通信套接字
    int cfd = socket(AF_INET, SOCK_STREAM, 0);
    if(cfd == -1)
    {
        perror("socket");
        return -1;
    }

    //2.连接服务器
    struct sockaddr_in saddr;
    saddr.sin_family = AF_INET;
    saddr.sin_port = htons(PORT_);
    inet_pton(AF_INET, IP_, &saddr.sin_addr.s_addr);

    int ret = connect(cfd, (struct sockaddr*)&saddr, sizeof(saddr));
    if(ret == -1)
    {
        perror("connect\n");
        return -1;
    }

    //3.向客户端发送数据
    int number = 0;//计数num
    while(1)
    {
        number++;//计数+1
        char buff[1024];
        // sprintf(buff, "你好， hello， world， %d", number);
        printf("请输入要发送的数据：");
        fgets(buff, sizeof(buff), stdin);
        
        send(cfd, buff, strlen(buff)+1, 0);

        //数组重置
        memset(buff, 0, sizeof(buff));

        int len = recv(cfd, buff, sizeof(buff), 0);
        if(len>0)
        {
            printf("Server say: %s\n", buff);            
        }
        else if(len == 0)
        {
            printf("服务器已经断开连接\n");
            break;
        }
        else
        {
            perror("recv");
            break;
        }

        sleep(1);
    }


    //4.关闭套接字
    close(cfd);

    return 0;
    

}